package com.heima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.reggie.common.R;
import com.heima.reggie.domain.Dish;
import com.heima.reggie.service.CategoryService;
import com.heima.reggie.service.DishService;
import com.heima.reggie.service.SetmealService;
import com.heima.reggie.domain.Category;
import com.heima.reggie.domain.Setmeal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    DishService dishService;
    @Autowired
    SetmealService setmealService;
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("添加分类 -------");
        categoryService.save(category);

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        log.info("page = {} , pageSize = {}", page, pageSize);
        Page page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByAsc(Category :: getSort);

        categoryService.page(page1,categoryLambdaQueryWrapper);
        return R.success(page1);
    }

    @DeleteMapping()
    public R<String> delete(Long ids){
        log.info("分类删除===========");
        List<Dish> dishes = dishService.selectDishByCategoryId(ids);
        List<Setmeal> setmeales = setmealService.selectSetmealByCategoryId(ids);
        if(dishes == null && setmeales == null){
            categoryService.removeById(ids);
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类===={}",category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());

        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
